from joystickshield import JoystickShield
from machine import SPI, Pin, ADC
import utime
import st7789
spi = SPI(0, baudrate=40000000, polarity=1, phase=0, bits=8, endia=0, sck=Pin(6), mosi=Pin(8))

# 全局变量
link = False
backgroud_color = st7789.color565(255, 255, 255)
text_color = color=st7789.color565(0, 0, 0)
mycolor = st7789.color565(255, 0, 0)
x_point = 0
y_point = 0
mylen = 24

# 初始化屏幕
screen = st7789.ST7789(spi, 240, 240, reset=Pin(11,func=Pin.GPIO, dir=Pin.OUT), dc=Pin(7,func=Pin.GPIO, dir=Pin.OUT))
screen.init()
screen.draw_string(50, 230, "Powered by BlackWalnuut Labs.")
screen.fill(backgroud_color)

# 实例化JoystickShield对象
pinA = Pin(14,Pin.IN)                                               #设置14号引脚为按钮A
pinB = Pin(0,Pin.IN)                                                #设置0号引脚为按钮B
pinC = Pin(1,Pin.IN)                                                #设置1号引脚为按钮C
pinD = Pin(2,Pin.IN)                                                #设置0号引脚为按钮D
adcX = ADC(Pin(12))                                                 #设置12号引脚为摇杆X轴
adcY = ADC(Pin(13))                                                 #设置13号引脚为摇杆Y轴
joystick = JoystickShield(pinA, pinB, pinC, pinD, adcX, adcY)

# 由于先开板子再开摇杆，会出现一段无连接时间
Nowdata = joystick.read()
while not([1, 1, 1, 1, 0, 0] == Nowdata):
    screen.draw_string(30, 100, "No signal", size=4, color = text_color)
    utime.sleep(0.5)
    Nowdata = joystick.read()
link = True
if link == True:
    screen.fill(st7789.color565(255, 255, 255))
    screen.draw_string(30, 100, "Welcome!", size=4, color = text_color)
    utime.sleep(2)

# 使用摇杆控制红色小方块在屏幕上移动
screen.fill(backgroud_color)
screen.fill_rect(x_point, y_point, mylen, mylen, mycolor)
while True:
    Nowdata = joystick.read()
    if Nowdata[0] == 0 or Nowdata[-1] == 1:                         # 向上移动,到边界了则不移动
        y_point = y_point-mylen if y_point > 0 else y_point
    elif Nowdata[2] == 0 or Nowdata[-1] == -1:                      # 向下移动,到边界了则不移动
        y_point = y_point+mylen if y_point < 216 else y_point
    elif Nowdata[3] == 0 or Nowdata[4] == -1:                       # 向左移动,到边界了则不移动
        x_point = x_point-mylen if x_point > 0 else x_point
    elif Nowdata[1] == 0 or Nowdata[4] == 1:                        # 向右移动,到边界了则不移动
        x_point = x_point+mylen if x_point < 216 else x_point
    screen.fill(backgroud_color)
    screen.fill_rect(x_point, y_point, mylen, mylen, mycolor)
    utime.sleep(0.1)                                                # 最小操作间隔为0.1s
